package com.LastingRunner;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.*;

import com.androidplot.xy.SimpleXYSeries;
import com.androidplot.series.XYSeries;
import com.androidplot.xy.*;
 
import java.text.*;
import java.util.*;

public class MainActivity extends Activity {
	private XYPlot DataPlot;
	private ListView DateList;
	private Button btnNewRun;
	private Context myContext = this;
	static final int NEW_RUN_REQUEST = 0;
	
	private void updateMainView()
	{
		List<String> listViewSrc = new LinkedList<String>();
		Number[] arrDate = null;
		Number[] arrLap = null;
		
		RunningDataOpenHelper runningData = new RunningDataOpenHelper(this);
		SQLiteDatabase RunningDataDB = runningData.getReadableDatabase();
		
		//Do query: total count of laps of everyday
		Cursor cur = RunningDataDB.query("RUNNING_DATA", new String[]{"DATE",
				"count(LAP) LAPS"},	null, null, "DATE", null, "DATE"); 
		
		if (cur != null && cur.moveToFirst()){
			int dateIndex = cur.getColumnIndex("DATE");
			int lapIndex = cur.getColumnIndex("LAPS");
			int nRow = cur.getCount();
			arrDate = new Number[nRow];
			arrLap = new Number[nRow];
			for (int i = 0;!cur.isAfterLast();cur.moveToNext(), ++i){
				Long date = new Long(cur.getLong(dateIndex));
				Long lap = new Long(cur.getLong(lapIndex));
				listViewSrc.add((new SimpleDateFormat("MM/dd/yy")).format(new Date(date))
						+ ": " + Long.toString(lap)+"lap(s)");
				arrDate[i] = date;
				arrLap[i] = lap;
			}
		} else {
			arrDate = new Number[]{0};
			arrLap = new Number[]{0};
		}
		
		// Initialize ListView with the date data
	    DateList.setAdapter(new ArrayAdapter<String>(this,R.layout.date_list_item,listViewSrc));
	    
	    // Initialize our XYPlot reference:
	    DataPlot = (XYPlot) findViewById(R.id.daily_chart);
	
	    // Create two arrays of y-values to plot:
	   
	    // Turn the above arrays into XYSeries:
	    RunningDataXYSeries series1 = new RunningDataXYSeries(
	    		arrDate,
	    		arrLap);
	            //"test");                            
	    
	    LineAndPointFormatter series1Format = new LineAndPointFormatter(
	            Color.rgb(0, 200, 0),                   // line color
	            Color.rgb(200, 0, 0),                   // point color
	            Color.rgb(150, 190, 150));              // fill color (optional)
	
	    // Add series1 to the xyplot:
	    DataPlot.setDomainValueFormat(new MyDateFormat());
	    DataPlot.addSeries(series1, LineAndPointRenderer.class, series1Format);
	
	    // Reduce the number of range labels
	    DataPlot.setTicksPerRangeLabel(1);
	    DataPlot.setTicksPerDomainLabel(4);
	    // Remove labels & legends
	    DataPlot.getDomainLabelWidget().setVisible(false);
        DataPlot.getRangeLabelWidget().setVisible(false);
        DataPlot.getLegendWidget().setVisible(false);
 
	    // By default, AndroidPlot displays developer guides to aid in laying out your plot.
	    // To get rid of them call disableAllMarkup():
	    DataPlot.setBorderStyle(XYPlot.BorderStyle.SQUARE, null, null);
	    DataPlot.disableAllMarkup();
		
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
	    super.onCreate(savedInstanceState);
	    setContentView(R.layout.main);
	    btnNewRun = (Button) findViewById(R.id.new_run);
	    DateList = (ListView) findViewById(R.id.date_list);
	    btnNewRun.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				startActivityForResult(new Intent(myContext, StopWatchActivity.class), NEW_RUN_REQUEST);
				
			}
		});
	    updateMainView();    
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		
	
	}
    private class MyDateFormat extends Format {
    	 
    	 
        /**
		 * 
		 */
		private static final long serialVersionUID = 1L;
		// create a simple date format that draws on the year portion of our timestamp.
        // see http://download.oracle.com/javase/1.4.2/docs/api/java/text/SimpleDateFormat.html
        // for a full description of SimpleDateFormat.
        private SimpleDateFormat dateFormat = new SimpleDateFormat("MM-dd");


        @Override
        public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) {
            long timestamp = ((Number) obj).longValue();
            Date date = new Date(timestamp);
            int d = date.getDate();
            int m = date.getMonth();
            return dateFormat.format(date, toAppendTo, pos);
        }

        @Override
        public Object parseObject(String source, ParsePosition pos) {
            return null;

        }

}
}
